import { useStreams } from '@/lib/utils'
import services from '@/services'
import { ContactType } from '@/services/contacts'

export function useQywxUnreads(focused: string | null) {
  const [metaUnreads, mutes] = useStreams(services.chat.metas.unreads, services.groups.mutes)

  const unreads = useMemo(() => {
    // 没有聚焦的企微时，不统计企微未读消息数
    if (focused === null) return undefined

    const unreads = new Map<string, number>()
    for (const item of metaUnreads.values()) {
      // 不统计当前聚焦的企微的未读消息数（因为联系人列表的分类一栏可看到）
      if (item.ownerWxid === focused) continue

      // 对于群，只统计未“静音”的群的未读消息数
      if (item.type === ContactType.group && mutes.has(item.contactId)) continue

      const prev = unreads.get(item.ownerWxid) ?? 0
      unreads.set(item.ownerWxid, prev + item.unread)
    }
    return unreads
  }, [focused, metaUnreads, mutes])

  return unreads
}
